#include "inc/internet.h"
#include "ui_internet.h"

internet::internet(QSerialPort *serialPort,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::internet),
    serialPort(serialPort)
{
    ui->setupUi(this);
    ui->label_5->hide();
    ui->label_6->hide();
    ui->wifiname->hide();
    ui->wifipassword->hide();
    ui->refresh->hide();
    scanAvailableWifiNetworks();
    readserver_and_port();
}

internet::~internet()
{
    delete ui;
}
void internet::scanAvailableWifiNetworks() {
    QProcess process;
    process.start("netsh", QStringList() << "wlan" << "show" << "networks");
    process.waitForFinished();

    QString output = QString::fromLocal8Bit(process.readAllStandardOutput());
    QStringList lines = output.split('\n');

    ui->wifiname->clear(); // 清空现有选项

    bool foundWifi = false;

    // 解析 netsh 输出，提取 SSID
    for (const QString &line : lines) {
        if (line.trimmed().startsWith("SSID")) {
            QString ssid = line.split(':').last().trimmed();
            if (!ssid.isEmpty()) {
                ui->wifiname->addItem(ssid);
                foundWifi = true;
            }
        }
    }

    // 如果没有找到 WiFi，添加提示
    if (!foundWifi) {
        ui->wifiname->addItem("未找到WiFi网络");
    }
}

void internet::on_refresh_clicked()
{
    scanAvailableWifiNetworks();
    QMessageBox::information(this, "刷新完成", "WiFi列表已刷新！");
}
void internet::readserver_and_port()
{
    if (!serialPort || !serialPort->isOpen()) {
        qDebug() << "Serial port not ready!";
        return;
    }

    QByteArray request;
    request.append(static_cast<char>(0xff));    // Slave address 00
    request.append(static_cast<char>(0x20));    // Function code 20
    request.append(static_cast<char>(0x00));    // Starting address high byte 00
    request.append(static_cast<char>(0x00));    // Starting address low byte 00
    request.append(static_cast<char>(0x00));    // Register count high byte 00
    request.append(static_cast<char>(0x02));    // Register count low byte 02

    // Calculate CRC16
    quint16 crc = calculateCRC(request);
    request.append(static_cast<char>(crc & 0xFF));      // CRC low byte
    request.append(static_cast<char>((crc >> 8) & 0xFF)); // CRC high byte

    if (serialPort->write(request) == -1) {
        qDebug() << "Write failed:" << serialPort->errorString();
        return;
    }

    // Read the response
    QByteArray response;
    if (serialPort->waitForReadyRead(1000)) {
        response = serialPort->readAll();
        while (serialPort->waitForReadyRead(100)) {
            response += serialPort->readAll();
        }
    } else {
        qDebug() << "Read timeout";
        return;
    }

    // Parse the response according to protocol: FF 20 dataLen(42) domain(32) port(32) crc
    if (response.size() >= 46) { // Minimum valid response size (4 header + 42 data + 2 crc)
        // Check response header
        if (static_cast<quint8>(response[0]) == 0xFF &&
            static_cast<quint8>(response[1]) == 0x20) {

            quint8 dataLength = static_cast<quint8>(response[2]);

            // Verify data length (should be 32 + 32 = 42)
            if (dataLength == 64) {
                // Extract domain (32 bytes)
                QByteArray domainBytes = response.mid(3, 32);
                QString domain = QString::fromLatin1(domainBytes).trimmed();

                // Extract port (10 bytes)
                QByteArray portBytes = response.mid(3 + 32, 10);
                QString portStr = QString::fromLatin1(portBytes).trimmed();

                // Update UI with the received data
                ui->server->setText(domain);
                ui->serverport->setText(portStr);

                qDebug() << "Server:" << domain << "Port:" << portStr;
            } else {
                qDebug() << "Invalid data length received:" << dataLength;
            }
        } else {
            qDebug() << "Invalid response header";
        }
    } else {
        qDebug() << "Response too short, size:" << response.size();
    }
}
void internet::on_pushButton_clicked()
{
    if (!serialPort || !serialPort->isOpen()) {
        qDebug() << "Serial port not ready!";
        return;
    }

    bool isWifi = (ui->net_type->currentText() == "WIFI");

    if (isWifi) {
        // Prepare WiFi credentials data
        QString wifiName = ui->wifiname->currentText();
        QString wifiPassword = ui->wifipassword->text();

        // Pad strings to 32 characters with zeros if needed
        wifiName = wifiName.leftJustified(32, '\0');
        wifiPassword = wifiPassword.leftJustified(32, '\0');

        QByteArray wifiRequest;
        wifiRequest.append(static_cast<char>(0xFF));  // Slave address FF
        wifiRequest.append(static_cast<char>(0x30));  // Function code 30
        wifiRequest.append(static_cast<char>(64));    // Data length (32+32)

        // Add WiFi name and password (64 bytes total)
        wifiRequest.append(wifiName.toLatin1());
        wifiRequest.append(wifiPassword.toLatin1());

        // Calculate CRC16
        quint16 crc = calculateCRC(wifiRequest);
        wifiRequest.append(static_cast<char>(crc & 0xFF));      // CRC low byte
        wifiRequest.append(static_cast<char>((crc >> 8) & 0xFF)); // CRC high byte

        if (serialPort->write(wifiRequest) == -1) {
            qDebug() << "WiFi settings write failed:" << serialPort->errorString();
            return;
        }

        // Read the response (just echo)
        QByteArray wifiResponse;
        if (serialPort->waitForReadyRead(1000)) {
            wifiResponse = serialPort->readAll();
            while (serialPort->waitForReadyRead(100)) {
                wifiResponse += serialPort->readAll();
            }
            qDebug() << "WiFi settings response:" << wifiResponse.toHex();
        } else {
            qDebug() << "WiFi settings read timeout";
            return;
        }
    }

    // Prepare server/port data (always sent, regardless of network type)
    QString server = ui->server->text();
    QString port = ui->serverport->text();

    // Pad strings to 32 characters with zeros if needed
    server = server.leftJustified(32, '\0');
    port = port.leftJustified(32, '\0');

    QByteArray serverRequest;
    serverRequest.append(static_cast<char>(0xFF));  // Slave address FF
    serverRequest.append(static_cast<char>(0x40));  // Function code 40
    serverRequest.append(static_cast<char>(64));    // Data length (32+32)

    // Add server and port (64 bytes total)
    serverRequest.append(server.toLatin1());
    serverRequest.append(port.toLatin1());

    // Calculate CRC16
    quint16 crc = calculateCRC(serverRequest);
    serverRequest.append(static_cast<char>(crc & 0xFF));      // CRC low byte
    serverRequest.append(static_cast<char>((crc >> 8) & 0xFF)); // CRC high byte

    if (serialPort->write(serverRequest) == -1) {
        qDebug() << "Server settings write failed:" << serialPort->errorString();
        return;
    }

    // Read the response (just echo)
    QByteArray serverResponse;
    if (serialPort->waitForReadyRead(1000)) {
        serverResponse = serialPort->readAll();
        while (serialPort->waitForReadyRead(100)) {
            serverResponse += serialPort->readAll();
        }
        qDebug() << "Server settings response:" << serverResponse.toHex();
    } else {
        qDebug() << "Server settings read timeout";
        return;
    }
    QByteArray Request;
    Request.append(static_cast<char>(0x00));  // Slave address FF
    Request.append(static_cast<char>(0x06));  // Function code 40
    Request.append(static_cast<char>(0x00));    // Data length (32+32)
    Request.append(static_cast<char>(0x04));    // Data length (32+32)
    // Add server and port (64 bytes total)
    Request.append(static_cast<char>(ui->net_type->currentIndex()>>8));    // Data length (32+32)
    Request.append(static_cast<char>(ui->net_type->currentIndex()&0xff));    // Data length (32+32)
    // Calculate CRC16
    quint16 crc1 = calculateCRC(Request);
    Request.append(static_cast<char>(crc1 & 0xFF));      // CRC low byte
    Request.append(static_cast<char>((crc1 >> 8) & 0xFF)); // CRC high byte

    if (serialPort->write(Request) == -1) {
        qDebug() << "Server settings write failed:" << serialPort->errorString();
        return;
    }
    QByteArray Response;
    if (serialPort->waitForReadyRead(1000)) {
        Response = serialPort->readAll();
        while (serialPort->waitForReadyRead(100)) {
            Response += serialPort->readAll();
        }
        qDebug() << "Server settings response:" << serverResponse.toHex();
    } else {
        qDebug() << "Server settings read timeout";
        return;
    }
    QMessageBox::information(this, "设置成功", "网络配置已保存！");
    emit netportConnect();
}

void internet::on_net_type_currentIndexChanged(int index)
{
    Q_UNUSED(index)
    bool isWifi = (ui->net_type->currentText() == "WIFI");
        ui->label_5->setVisible(isWifi);
        ui->label_6->setVisible(isWifi);
        ui->wifiname->setVisible(isWifi);
        ui->wifipassword->setVisible(isWifi);
        ui->refresh->setVisible(isWifi);
}
